package com.yygo.jobs;

import com.yygo.model.SettlementTask;
import com.yygo.service.SettlementTaskManager;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import java.util.Collection;

/**
 * Created by huanli on 2015/11/28.
 */
public class SettlementJob{
    public void initTask() throws Exception {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        Collection<SettlementTask> taskList = taskService.getAll();
        for (SettlementTask task : taskList) {
            TriggerKey triggerKey = TriggerKey.triggerKey(
                    "task_" + task.getId(), "group_" + task.getId());
            CronTrigger trigger = (CronTrigger) scheduler
                    .getTrigger(triggerKey);
            if (null == trigger) {
                JobDetail jobDetail = JobBuilder
                        .newJob(SettlementTaskFactory.class)
                        .withIdentity("task_" + task.getId(),
                                "group_" + task.getId()).build();
                jobDetail.getJobDataMap().put("scheduleJob", task);
                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder
                        .cronSchedule(task.getCronExpression());
                trigger = TriggerBuilder
                        .newTrigger()
                        .withIdentity("task_" + task.getId(),
                                "group_" + task.getId())
                        .withSchedule(scheduleBuilder).build();
                scheduler.scheduleJob(jobDetail, trigger);
            } else {
                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder
                        .cronSchedule(task.getCronExpression());
                trigger = trigger.getTriggerBuilder().withIdentity(triggerKey)
                        .withSchedule(scheduleBuilder).build();
                scheduler.rescheduleJob(triggerKey, trigger);
            }
        }
    }
    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;
    @Autowired
    private SettlementTaskManager taskService;
}
